<!--图文管理-->
<template>
  <div id="imageTextCreate" class="app-container">
    <el-form
      ref="dataForm"
      :rules="thirdWechatArticleRules"
      :model="thirdWechatArticleRecord"
      label-position="right"
      label-width="120px">
      <DocEditor
        :form="{
          title:thirdWechatArticleRecord.title,
          contnetAbstract:thirdWechatArticleRecord.summary,
          content:thirdWechatArticleRecord.contentBody
        }"
        :catalog="constants.FILE_CATALOG_WECHAT_ARTICLE_CONTENT"
        :error="errorMsg"
        :show-input="['abstract']"
        @result="handleEditorResult">
        <template>
          <el-form-item label="作者:" prop="author">
            <el-input v-model="thirdWechatArticleRecord.author" maxlength="10" show-word-limit placeholder="请输入文章作者" clearable />
          </el-form-item>
          <el-form-item label="所属分类:" prop="categoryId">
            <el-select-tree v-model="thirdWechatArticleRecord.categoryId" :data="categories" :props="{children: 'children', label: 'name'}" />
          </el-form-item>
          <el-form-item label="原创:">
            <el-switch
              v-model="thirdWechatArticleRecord.isOriginal"
              active-color="#4a5dff"
              :active-value="1"
              :inactive-value="0" />
          </el-form-item>
          <template v-if="thirdWechatArticleRecord.isOriginal===0">
            <el-form-item label="来源:" prop="source">
              <el-input v-model="thirdWechatArticleRecord.source" maxlength="50" show-word-limit placeholder="请输入文章来源" clearable />
            </el-form-item>
            <el-form-item label="链接:" prop="sourceUrl">
              <el-input v-model="thirdWechatArticleRecord.sourceUrl" maxlength="100" show-word-limit placeholder="请输入文章来源链接" clearable>
                <el-button slot="append" icon="el-icon-search" @click="handleGoSourceUrl" />
              </el-input>
            </el-form-item>
          </template>
        </template>
        <template slot="bottom">
          <el-form-item label="封面:" prop="photo">
            <single-image-upload v-model="thirdWechatArticleRecord.photo" :crop-ratio="2 / 1" :catalog="constants.FILE_CATALOG_WECHAT_ARTICLE_PHOTO" />
          </el-form-item>
          <el-row>
            <el-col :span="8">
              <el-form-item label="收藏次数:" prop="collectCount">
                <el-input v-model="thirdWechatArticleRecord.collectCount" oninput="value=value.replace(/\D/g, '')" show-word-limit placeholder="请输入初次收藏次数" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="浏览总数:" prop="viewCount">
                <el-input v-model="thirdWechatArticleRecord.viewCount" oninput="value=value.replace(/\D/g, '')" show-word-limit placeholder="请输入初次浏览总数" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="点赞次数:" prop="likeCount">
                <el-input v-model="thirdWechatArticleRecord.likeCount" oninput="value=value.replace(/\D/g, '')" show-word-limit placeholder="请输入初次点赞次数" clearable />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="置顶:">
            <el-switch
              v-model="thirdWechatArticleRecord.isTop"
              active-color="#4a5dff"
              :active-value="1"
              :inactive-value="0" />
          </el-form-item>
          <el-form-item label="留言:" prop="leavingMessage">
            <el-radio-group v-model="thirdWechatArticleRecord.leavingMessage">
              <el-radio :label="0">禁止留言</el-radio>
              <el-radio :label="1">所有人可留言</el-radio>
              <el-radio :label="2">仅粉丝可留言</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="附件:" prop="attachment1">
            <simple-uploader v-model="thirdWechatArticleRecord.attachment1" :catalog="constants.FILE_CATALOG_WECHAT_ARTICLE_ATTACHMENT" />
          </el-form-item>
        </template>
        <template slot="footer">
          <el-button type="default" plain @click="status==='create'?createData(0):updateData(0)">暂存 </el-button>
          <el-button type="primary" plain @click="status==='create'?createData(1):updateData(1)">仅保存 </el-button>
          <el-button plain @click="handleGoBack">返回</el-button>
        </template>
        <template slot="desc">
          向下滑动鼠标，还有内容哟！
        </template>
      </DocEditor>
    </el-form>
  </div>
</template>

<script>
export default {
  components: {},

  data() {
    return {
      resourceType: 4,
      appId: '',
      categories: [],
      status: 'create',
      errorMsg: null,
      thirdWechatArticleRecord: {},
      thirdWechatArticleRules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        author: [
          { required: true, message: '请输入责任编辑', trigger: 'blur' }
        ],
        photo: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择所属分类', trigger: 'blur' }
        ],
        viewCount: [
          { required: true, message: '请输入浏览总数', trigger: 'blur' }
        ],
        likeCount: [
          { required: true, message: '请输入点赞次数', trigger: 'blur' }
        ],
        collectCount: [
          { required: true, message: '请输入收藏次数', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入正文', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
  },
  created() {
    this.init()
  },

  methods: {
    init() {
      var id = this.$route.query.id
      this.appId = this.$route.params.appId
      if (this.appId) {
        this.fetchCategories()
      }
      if (id) {
        this.handleUpdate(id)
      } else {
        this.handleCreate()
      }
    },
    async fetchCategories() {
      var res = await this.$store.dispatch('thirdWechatResourceCategoryTree', { appId: this.appId, type: this.resourceType })
      this.categories = res
    },
    handleEditorResult(val) {
      this.thirdWechatArticleRecord = {
        ...this.thirdWechatArticleRecord,
        title: val.title,
        summary: val.contnetAbstract,
        contentBody: val.content
      }
    },
    handleGoBack() {
      this.$router.push({ name: 'materialLibraryImageText' })
      const view = this.$route
      delete view.icon
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {})
    },
    /* 新增*/
    handleCreate() {
      this.thirdWechatArticleRecord = {
        leavingMessage: 0,
        isOriginal: 1,
        attachment1: [],
        appId: this.appId,
        resourceType: this.resourceType,
        likeCount: 0,
        viewCount: 0,
        collectCount: 0
      }
      this.status = 'create'
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData(status) {
      if (!this.T.removeHtmltag(this.thirdWechatArticleRecord.title)) {
        this.errorMsg = '请填写标题'
        return true
      }
      if (!this.T.removeHtmltag(this.thirdWechatArticleRecord.contentBody)) {
        this.errorMsg = '请填写正文内容'
        return true
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          var tempData = Object.assign({}, this.thirdWechatArticleRecord)
          tempData.attachment = tempData.attachment1.join(',')
          tempData = {
            ...tempData,
            status: status
          }
          delete tempData.attachment1
          this.$store.dispatch('thirdWechatArticleSave', tempData).then(response => {
            if (status === 0) {
              this.$modal.msgSuccess('暂存成功')
              this.$router.push({ name: 'materialLibraryImageTextCreate', params: { appId: this.appId }, query: { id: response.id }})
            } else {
              this.$confirm('创建成功', '提示', {
                confirmButtonText: '新增图文',
                cancelButtonText: '图文列表',
                type: 'warning'
              }).then(() => {
                this.$router.push({ name: 'materialLibraryImageTextCreate', params: { appId: this.appId }, query: { }})
                this.init()
              }).catch(() => {
                this.handleGoBack()
              })
            }
          }).catch(() => {
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(id) {
      this.status = 'update'
      this.$nextTick(() => {
        this.$store.dispatch('thirdWechatArticleGetDetailsById', id).then(res => {
          this.thirdWechatArticleRecord = {
            ...res,
            attachment1: res.attachment === null ? [] : res.attachment.split(',')
          }
        }).catch(() => {})
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData(status) {
      if (!this.T.removeHtmltag(this.thirdWechatArticleRecord.title)) {
        this.errorMsg = '请填写标题'
        return true
      }
      if (!this.T.removeHtmltag(this.thirdWechatArticleRecord.contentBody)) {
        this.errorMsg = '请填写正文内容'
        return true
      }
      if (this.thirdWechatArticleRecord.isOriginal === 1) {
        this.thirdWechatArticleRecord = {
          ...this.thirdWechatArticleRecord,
          source: '',
          sourceUrl: ''
        }
      }
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.thirdWechatArticleRecord)
          if (status === 1) {
            tempData.status = 1
          }
          tempData.attachment = tempData.attachment1.join(',')
          delete tempData.attachment1
          this.$store.dispatch('thirdWechatArticleUpdate', tempData).then(response => {
            if (status === 0) {
              this.$modal.msgSuccess('暂存成功')
            } else {
              this.$confirm('修改成功', '提示', {
                confirmButtonText: '新增图文',
                cancelButtonText: '图文列表',
                type: 'warning'
              }).then(() => {
                this.$router.push({ name: 'materialLibraryImageTextCreate', params: { appId: this.appId }, query: { }})
                this.init()
              }).catch(() => {
                this.handleGoBack()
              })
            }
          }).catch(() => {
          })
        }
      })
    },
    handleGoSourceUrl() {
      if (!this.thirdWechatArticleRecord.sourceUrl) {
        return
      }
      window.open(this.thirdWechatArticleRecord.sourceUrl, '_blank')
    }
  }
}
</script>
<style lang="scss">
#imageTextCreate{
  background-color: #fff;
}
</style>
